package internal

import (
	"github.com/BurntSushi/toml"
	"sync"
	"talent.com/server/durotar.git/leaf"
	"talent.com/server/durotar.git/log"
)

var (
	scLock sync.RWMutex
	scInst *serverConfig
)

type serverConfig struct {
	Server *serverConf
	DB     *dbConf
	Log    *logConf
	Redis  *redisConf
	Qiniu  *qiniuConf
	Pay    *payConf
}

type dbConf struct {
	Host    string
	IsDebug bool `toml:"Debug"`
}

type logConf struct {
	Path  string
	Level string
}

type serverConf struct {
	WSAddr   string
	HTTPAddr string
	URL      string
}

type redisConf struct {
	Host     string
	Password string
	Index    int
}

type qiniuConf struct {
	AccessKey   string
	SecretKey   string
	ImageBucket string
	ImageHost   string
}

type payConf struct {
	Host             string
	ApiKey           string
	AgencyPlatformID uint64
	PayFrontHost     string
	PayOperatorID    uint64
	TelegramGroupID  string
}

func ReloadServerConfig(path string, isReload bool) {
	var sc serverConfig
	if _, err := toml.DecodeFile(path, &sc); err != nil {
		panic(err)
	}
	if !isReload {
		log.InitLogger(sc.Log.Level, sc.Log.Path)
		if sc.Log.Level == "debug" {
			leaf.ConfigLog(true)
		} else {
			leaf.ConfigLog(false)
		}
	} else {
		log.ReloadLogger(sc.Log.Level)
	}
	scLock.Lock()
	scInst = &sc
	scLock.Unlock()
}

func GetServerConfig() *serverConfig {
	scLock.RLock()
	defer scLock.RUnlock()
	return scInst
}
